import { HttpException, Injectable, Logger } from '@nestjs/common';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import * as crypto from 'crypto';

function md5(str) {
  const hash = crypto.createHash('md5');
  hash.update(str);
  return hash.digest('hex');
}


@Injectable()
export class UserService {

  private logger = new Logger();

  @InjectRepository(User)
  private useRepository: Repository<User>;


  async register(user: RegisterDto) {
    const finduser = await this.useRepository.findOneBy({ username: user.username });
    if (finduser) throw new HttpException('用户已存在', 200);

    try {
      await this.useRepository.save({ username: user.username, password: md5(user.password) });
      return '注册成功';
    } catch (e) {
      this.logger.error(e, UserService);
      return '注册失败';
    }
  }



  async login(user: LoginDto) {
    const finduser = await this.useRepository.findOneBy({ username: user.username });

    if(!finduser){
      throw new HttpException('用户不存在或密码有误', 200);
    } 

    if(finduser.password !== md5(user.password)){
      throw new HttpException('用户不存在或密码有误', 200);
    }

    return finduser;
    
  }

}
